<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申购单号" prop="requisitionForm">
        <el-input
          v-model="queryParams.requisitionForm"
          placeholder="请输入申购单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图纸图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="需求交期" prop="requirementTime">
        <el-date-picker
          v-model="queryParams.requirementTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['outsource:outbound-delivery-goods-detail:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="createArrivalNote"
          :loading="exportLoading"
          v-hasPermi="['outsource:outbound-delivery-goods-detail:create']"
        >
          创建到货单
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      border
      :summary-method="getSummaries"
      show-summary
      row-key="id"
      :height="tableHeight"
      default-expand-all
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      :row-style="rowStyle"
    >
      <el-table-column
        align="center"
        :selectable="isSelected"
        :reserve-selection="true"
        type="selection"
        fixed="left"
        width="80"
      />
      <!-- :class="{ fontColor: scope.row.dictQualityGateStatus == 20 }" -->
      <el-table-column label="序号" align="center" type="index" fixed="left" width="80" />
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
          v-if="item.isTable && item.label != '序号'"
          :key="index"
          :type="item.type"
          :min-width="item.width"
          :header-align="item.headerAlign"
          :align="item.align"
          :label="item.label"
          :prop="item.field"
          :tree-props="{ children: 'children' }"
          row-key="id"
        >
          <template #default="scope">
            <template v-if="item.field === 'arriveQuantity'">
              <!-- 到货数量 -->
              <el-input
                v-nextInput="'arriveQuantity'"
                name="arriveQuantity"
                type="number"
                :min="0"
                v-model="scope.row.arriveQuantity"
              />
            </template>
            <template v-else>
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <span v-else>{{ scope.row[item.field] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="OutboundDeliveryGoodsDetail">
import download from '@/utils/download'
import * as OutboundDeliveryGoodsDetailApi from '@/api/outsource/outsourceInAndOutStorage/outboundDeliveryGoodsDetail'
const message = useMessage()
const { push } = useRouter()
const total = ref(0) // 列表的总页数
const list = ref<any[]>([]) // 列表的数据
const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
const multipleTableRef = ref()
const loading = ref(false) // 列表的加载中
const isEdit = ref(false) //是否指派

const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  orderNumber: null,
  supplierName: null,
  salesName: null,
  requisitionForm: null,
  productNumber: null,
  partName: null,
  drawingNumber: null,
  requirementTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const getSummaries = (param) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    }
    if (['arriveQuantity'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    } else if (['purchaseQuantity'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    } else if (['quantityCollected'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    }
  })

  return sums
}
/**数据 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OutboundDeliveryGoodsDetailApi.getOutboundDeliveryGoodsDetailPage(
      queryParams
    )
    list.value = data.list
    tableTitleList.value = data.labels
    total.value = data.total
    loading.value = false
  } finally {
    loading.value = false
  }
}
const rowStyle = (row) => {
  console.log(row)
  if (row.dictQualityGateStatus == 20) {
    return { color: 'red' }
  }
}

// 多选是否启用
const isSelected = (row) => {
  if (isEdit.value) {
    if (row.dictReportWay === 10) {
      return true
    } else {
      return row.parent !== undefined ? true : false
    }
  } else {
    return true
  }
}

/**选中 */
const selectList = ref<any[]>([])
const handleSelectionChange = (data) => {
  selectList.value = data
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/**打开表格表头设置**/
const tableTitleSet = ref()
const openTableTitleSet = () => {
  let code = 'OutboundDeliveryGoodsDetail'
  tableTitleSet.value.open(tableTitleList.value, code)
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}
// 导出
const downloadFun = async () => {
  const val = exportRef.value.params
  let params = {
    fileName: val.name,
    ids: ''
  }
  if (val.range === 'all') {
    params.ids = ''
  } else {
    params.ids = selectList.value.map((item) => item.id).join(',')
  }
  OutboundDeliveryGoodsDetailApi.exportOutboundDeliveryGoodsDetail(params).then((res) => {
    download.excel(res, val.name)
    clearSelectData()
  })
}

//清空多选
const clearSelectData = () => {
  selectList.value = []
  multipleTableRef.value.clearSelection()
}
//创建到货单
const createArrivalNote = async () => {
  let data = await selectList.value
  if (data.length) {
    push({
      path: '/outsource/outsource/warehousingOutbound/OutboundDeliveryGoodsDetailForm',
      query: { list: JSON.stringify(data) }
    })
  } else {
    message.warning('请勾选数据')
  }
}

/** 初始化 **/
const tableHeight = ref(0)
onMounted(async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
  getList()
})
</script>
